package com.servlet;

import org.apache.log4j.Logger;

import javax.annotation.Resource;
import javax.jms.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/send")
public class MessageSender extends HttpServlet {
    public static final Logger LOG = Logger.getLogger(MessageSender.class);

    //@Resource(mappedName="java:app/jms/myDestFactory")
    @Resource(mappedName="jms/myDestinationFactory")
    private ConnectionFactory connectionFactory;

    //@Resource(mappedName="java:app/jms/dest")
    @Resource(mappedName="jms/myDestination")
    private Destination queue;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        String message = req.getParameter("msg");
        try
        {
            send(message);
        } catch (JMSException ex)
        {
            LOG.error("JMSException: " + ex);
            throw new ServletException(ex);
        }
        resp.sendRedirect(req.getContextPath() + "/index.jsp");
    }

    private void send(String text) throws JMSException
    {
        Connection connection = connectionFactory.createConnection();
        try
        {
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer producer = session.createProducer(queue);
            producer.send(session.createTextMessage(text));
        }
        finally
        {
            connection.close();
        }
    }
}